package priv.stones.common.aop;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import priv.stones.common.annotation.CommitLog;
import priv.stones.common.utils.ServletHelper;
import priv.stones.controller.administrate.shiro.ShiroUtils;
import priv.stones.entity.SysAdmin;
import priv.stones.entity.SysCommitlog;
import priv.stones.service.SysCommitlogService;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Author: Stones
 * @Description:
 * @Date: 2017/10/23 15:16
 */
@Aspect
@Component
public class CommitLogAspect {

    @Autowired
    private SysCommitlogService sysCommitlogService;

    @Pointcut("@annotation(priv.stones.common.annotation.CommitLog)")
    public void CommitLogPointCut() {
    }

    @Around("CommitLogPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        //执行方法
        Object result = point.proceed();
        //保存日志
        saveSysLog(point);
        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SysAdmin sysAdmin = ShiroUtils.getAdmin();
        if (sysAdmin != null) {
            if (sysAdmin.getName().equals(ShiroUtils.SuperAdmin)) {
                return;
            }
            SysCommitlog sysCommitlog = new SysCommitlog();
            //请求方法名
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = signature.getName();
            sysCommitlog.setMethod(className + "." + methodName + "()");
            //请求参数
            sysCommitlog.setParams(JSON.toJSONString(joinPoint.getArgs()));
            //事件(描述)
            Method method = signature.getMethod();
            CommitLog commitLog = method.getAnnotation(CommitLog.class);
            if (commitLog != null) {
                sysCommitlog.setEventsignature(commitLog.value());
            }
            sysCommitlog.setIp(ServletHelper.getIpAddress(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()));
            sysCommitlog.setAdmin(ShiroUtils.getAdmin().getId());
            sysCommitlog.setCommittime(new Date());
            sysCommitlogService.insert(sysCommitlog);
        }
    }

}
